package hu.gar.core.security;

import hu.gar.common.service.UserService;
import hu.gar.vo.RoleVO;
import hu.gar.vo.UserVO;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service(value = "authenticationProvider")
public class CustomAuthenticationProvider implements
		org.springframework.security.authentication.AuthenticationProvider {

	@Autowired
	UserService service;

	@Override
	public Authentication authenticate(Authentication authentication)
			throws AuthenticationException {

		String principal = (String) authentication.getPrincipal();

		String credentials = (String) authentication.getCredentials();

		try {
			service.authenticate(principal, credentials);
			UserVO userVO = service.findByName(principal);
			Collection<GrantedAuthority> roles = new HashSet<GrantedAuthority>();

			List<RoleVO> roleVOs = service.getRolesByUserId(userVO.getId());
			for (RoleVO role : roleVOs) {
				roles.add(new SimpleGrantedAuthority(role.getRole()));
			}

			SpringAuthentication springAuthentication = new SpringAuthentication(
					roles, userVO.getUsername());

			springAuthentication.setAuthenticated(true);
			return springAuthentication;

		} catch (BadCredentialsException e) {
			throw new UsernameNotFoundException(
					(String) authentication.getPrincipal());

		} catch (Exception e) {
			throw new UsernameNotFoundException(
					(String) authentication.getPrincipal());
		}

	}

	@Override
	public boolean supports(Class<?> arg0) {
		// TODO RememberMeAuthenticationToken ha kell
		if (arg0 == UsernamePasswordAuthenticationToken.class) {
			return true;
		}
		return false;
	}

}